module.exports = (function () {
	let fs = require("fs"),
		url = require("url"),
		path = require("path"),
		querystring = require("querystring"),
		UUID = require("uuid"),
		database = require("./database.js");

	let routes = {
		"api/register": function (request, response) {
			// params = { name: "string", password: "string"}
			var post_data = "";
			request.on("data", function (chunk) {
				post_data += chunk;
			});
			request.on("end", function () {
				post_data = querystring.parse(post_data);
				console.log("post_data");
				console.log(post_data);
				if (post_data.name && post_data.password) {
					 response.writeHead(200, {'Content-Type': 'text/plain; charset=utf8'});
					 var res = {
					 	message: "login success",
					 	status: "1",
					 	data:""
					 }
					 database.connectDB(function (connection,result) {
					 	console.log("connect csblog success...");
					 	var uid = UUID.v1();
					 	console.log("uid:"+uid);
					 	var sql_str = `INSERT INTO users(uid,name,phonenum,password) 
					 	VALUES ('${uid}','${post_data.name}','${post_data.phonenum}','${post_data.password}')
					 	`;
					 	connection.query(sql_str, function (err, result) {
					 		if (err) {
					 			
					 			if (err.errno == "1146") {
					 				var create_table = "CREATE TABLE IF NOT EXISTS users("+
					 					"uid VARCHAR(200) NOT NULL,"+
					 					"name VARCHAR(30) NOT NULL,"+
					 					"phonenum VARCHAR(50) NOT NULL,"+
					 					"password VARCHAR(50) NOT NULL,"+
					 					"PRIMARY KEY (uid)"+
					 				")";
					 				connection.query(create_table, function (err, result) {
					 					if (err) {
					 						console.log(err);
					 						return;
					 					}
					 					connection.query(sql_str, function (err, result) {
					 						if (err) {
					 							console.log(err);
					 							return;
					 						}
					 						else {
					 							console.log("insert user success...")
					 						}
					 					})
					 				})
					 			}
					 			console.log(err);
					 			return;
					 		}
					 		console.log("insert user success...");
					 		console.log(result);
					 	})
					 });
					 response.write(JSON.stringify(res));
					 response.end();
				}
			})
			
		}
	}
	return {
		request: function (query_params, request, response){
			routes[query_params["s"]](request, response);
		}
	};
})()